package com.song.tools.songtest.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.song.tools.core.exception.BusinessException;
import com.song.tools.core.exception.ExceptionCodeEnum;
import com.song.tools.core.util.ObjectUtils;
import com.song.tools.mvc.request.PageRequest;
import com.song.tools.mvc.response.PageResponse;
import com.song.tools.mvc.validator.ValidationException;
import com.song.tools.mvc.validator.ValidationResult;
import com.song.tools.songtest.beans.bo.OperateLogBo;
import com.song.tools.songtest.beans.query.OperateLogQuery;
import com.song.tools.songtest.beans.request.OperateLogQueryRequest;
import com.song.tools.songtest.beans.request.OperateLogSaveRequest;
import com.song.tools.songtest.beans.response.OperateLogQueryResponse;
import com.song.tools.songtest.beans.response.OperateLogSaveResponse;
import com.song.tools.songtest.convertor.OperateLogConvertor;
import com.song.tools.songtest.dao.entity.OperateLog;
import com.song.tools.songtest.manager.OperateLogManager;
import com.song.tools.songtest.service.OperateLogService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 操作日志表 服务实现类
 * </p>
 *
 * @author song tools
 * @since 2024-07-16
 */
@Slf4j
@Service
public class OperateLogServiceImpl implements OperateLogService {

    @Resource
    private OperateLogManager operateLogManager;

    @Resource
    private OperateLogConvertor operateLogConvertor;

    private static final Map<String, SFunction<OperateLog, ?>> COLUMNS_FUNCTION_MAP;
    static {
        COLUMNS_FUNCTION_MAP = Map.of(
                "id", OperateLog::getId,
                "logId", OperateLog::getLogId
        );
    }


    /**
     * 通过唯一key查询单个数据
     *
     * @param uniqueKey 唯一键
     * @param column    列名
     * @return 单个数据查询响应结果
     */
    @Override
    public OperateLogQueryResponse getOneByUniqueKey(Object uniqueKey, String column) {
        // 根据业务ID查询
        OperateLogBo operateLogBo = operateLogManager.getOneByUniqueKey(uniqueKey, COLUMNS_FUNCTION_MAP.getOrDefault(column, OperateLog::getId));
        return operateLogConvertor.entityBoToQueryResponse(operateLogBo);
    }

    /**
     * 查询信息（不分页）
     *
     * @param request 请求
     * @return 响应
     */
    @Override
    public List<OperateLogQueryResponse> list(OperateLogQueryRequest request) {
        OperateLogQuery operateLogQuery = operateLogConvertor.queryRequestToQuery(request);
        if (ObjectUtils.isNotEmpty(operateLogQuery)) {
            List<OperateLogBo> operateLogList = operateLogManager.list(operateLogQuery);
            if (ObjectUtils.isNotEmpty(operateLogList)) {
                return operateLogList.stream()
                        .map(operateLogConvertor::entityBoToQueryResponse)
                        .filter(ObjectUtils::isNotEmpty)
                        .collect(Collectors.toList());
            }
        }
        return Collections.emptyList();
    }


    /**
     * 查询信息（分页）
     *
     * @param request 请求
     * @return PageResponse 响应
     */
    @Override
    public PageResponse<OperateLogQueryResponse> listPages(PageRequest<OperateLogQueryRequest> request) {
        try {
            // 分页查询
            IPage<OperateLogBo> operateLogPage = operateLogManager.page(transformToQuery(request));

            // 安全地处理分页转换逻辑
            return safelyConvertPage(operateLogPage);
        } catch (Exception e) {
            log.error("查询失败", e);
            throw new BusinessException(ExceptionCodeEnum.SELECT_ERROR);
        }
    }


    /**
     * 安全地将分页数据转换为响应对象
     *
     * @param operateLogPage 分页查询结果
     * @return 分页响应对象
     */
    private PageResponse<OperateLogQueryResponse> safelyConvertPage(IPage<OperateLogBo> operateLogPage) {
        if (operateLogPage == null || operateLogPage.getRecords() == null) {
            return new PageResponse<>();
        }

        // 使用并行流进行转换以提高效率，但需确保线程安全
        List<OperateLogQueryResponse> responses = operateLogPage.getRecords().parallelStream()
            .map(operateLogBo -> operateLogConvertor.entityBoToQueryResponse(operateLogBo))
            .collect(Collectors.toList());

        return PageResponse.convertPage(operateLogPage, responses);
    }


    /**
     * 将请求 request 转换成 manager 的 query 对象
     *
     * @param request 请求参数
     * @return query 对象
     */
    private PageRequest<OperateLogQuery> transformToQuery(PageRequest<OperateLogQueryRequest> request) {
        OperateLogQuery operateLogQuery = operateLogConvertor.queryRequestToQuery(request.getData());
        return new PageRequest<>(request.getPageNum(), request.getPageSize(), operateLogQuery);
    }


    /**
     * 新增
     *
     * @param saveRequest 请求入参
     * @return 响应
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OperateLogSaveResponse save(OperateLogSaveRequest saveRequest) {
        // 校验请求入参
        ValidationResult validationResult = validateOnSave(saveRequest);
        if (!validationResult.isValid()) {
            throw ValidationException.message(validationResult.getErrorMessage());
        }

        // 根据入参封装 BO对象
        OperateLogBo operateLogBo = operateLogConvertor.saveRequestToEntityBo(saveRequest);

        // 数据库操作：插入数据
        int rows = operateLogManager.save(operateLogBo);

        // 处理插入结果
        boolean saveSuccess = rows > 0;
        // 新增数据成功，返回结果
        if (saveSuccess) {
            // 修改后的数据通过数据库查询返回
            OperateLogBo savedOperateLogBo = operateLogManager.getOneByUniqueKey(operateLogBo.getId(), OperateLog::getId);
            return operateLogConvertor.entityBoToSaveResponse(savedOperateLogBo);
        }

        // 新增数据失败，抛出异常
        throw new BusinessException(ExceptionCodeEnum.CREATE_ERROR);
    }
}
